package bg.cinema_system.beans;

import java.sql.SQLException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import bg.cinema_system.pojo.User;
import bg.cinema_system.service.UserServeice;

@ManagedBean
@SessionScoped
public class LoginBean {

	private String username;
	private String password;
	private String warning;

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	public String getWarning() {
		return warning;
	}

	public void setWarning(String warning) {
		this.warning = warning;
	}

	public String login() {
		User user = null;
		try {
			user = (UserServeice.isUserExist(getUsername(), getPassword()));
		} catch (SQLException e) {
			setWarning("Invalid username or password. Please try again.");
			return "login";
		}

		if (user.getUserId() != 0) {
			HttpSession session = (HttpSession) FacesContext
					.getCurrentInstance().getExternalContext().getSession(true);
			session.setAttribute("userId", user.getUserId());
			session.setAttribute("userRole", user.getRole());

			if (user.getRole() == 1) {
				return "user_daily_program";
			}

			if (user.getRole() == 2) {
				return "user_daily_program";
			}

			if (user.getRole() == 3) {
				return "user_daily_program";
			}
		}

		setWarning("Invalid username or password. Please try again.");
		return "login";

	}

	public String logout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);

		if (session != null) {
			session.setAttribute("userId", 0);
			session.setAttribute("userRole", 0);
			session.removeAttribute("userId");
			session.removeAttribute("userRole");
			session.invalidate();
		}

		return "login";
	}

}
